<script>
import { Decimal } from "decimal.js-light";
import {
  addOtherOrder,
  getAddressList,
  getOneByCode,
  getPickUpList,
} from "@/config/api";
import { mapState } from "vuex";
import tabs from "@/components/tabs/tabs.vue";
import { payTransactions } from "@/utils";

export default {
  components: {
    tabs,
  },
  data() {
    return {
      tabs: [
        {
          id: 1,
          name: "快递邮寄",
        },
        {
          id: 2,
          name: "自提",
        },
      ],
      tabActive: 1,
      addressInfo: {},
      isFreight: false,
      freight: 0,
      pickUpInfo: {},
      pickUpUserInfo: {
        phone: "",
        name: "",
      },
      isSubmitting: false,
    };
  },
  computed: {
    ...mapState([
      "settlementGoods",
      "selectAddress",
      "selectPickUpPoint",
      "selectPickUpInfo",
    ]),
    sourceList() {
      return this.settlementGoods;
    },
    list() {
      return this.formatData(this.sourceList);
    },
    toShowFreight() {
      return Number(`${this.freight}e-2`).toFixed(2);
    },
    goodsCountNum() {
      return this.list.reduce((acc, store) => {
        return acc + store.goods.length;
      }, 0);
    },
    goodsCountPrice() {
      return new Decimal(
        this.list.reduce((acc, store) => {
          return store.goods.reduce((_acc, goods) => {
            return new Decimal(goods.price)
              .div(100)
              .mul(goods.goodsNum)
              .add(_acc)
              .toNumber();
          }, acc);
        }, 0)
      )
        .add(this.tabActive === 1 ? Number(`${this.freight}e-2`) : 0)
        .toFixed(2);
    },
    deliveryInfo() {
      if (this.tabActive === 1) {
        return {
          address:
            this.addressInfo.provinceName +
            this.addressInfo.cityName +
            this.addressInfo.countyName,
          addressDetail: this.addressInfo.address,
          userName: this.addressInfo.name,
          userPhone: this.addressInfo.phone,
        };
      }
      if (this.tabActive === 2) {
        return {
          address:
            this.pickUpInfo.provinceName +
            this.pickUpInfo.cityName +
            this.pickUpInfo.countyName,
          addressDetail: this.pickUpInfo.address,
          userName: this.pickUpUserInfo.name,
          userPhone: this.pickUpUserInfo.phone,
        };
      }
    },
  },
  onLoad() {},
  onShow() {
    this.pickUpUserInfo.name =
      this.selectPickUpInfo.name || this.userInfo.nickName;
    this.pickUpUserInfo.phone =
      this.selectPickUpInfo.phone || this.userInfo.phonenumber;
    this.getAddressList().then(() => {
      if (
        this.addressInfo.city ||
        this.addressInfo.county ||
        this.addressInfo.province
      ) {
        this.getFreight();
      }
    });
    this.getPickUpList();
  },
  methods: {
    placeOrder() {
      if (this.isSubmitting) {
        uni.showToast({ title: "正在拉起支付", icon: "none" });
        return;
      }
      if (!this.deliveryInfo.address || !this.deliveryInfo.addressDetail) {
        if (this.tabActive === 1) {
          uni.showToast({ title: "请选择收货地址", icon: "none" });
        }
        if (this.tabActive === 2) {
          uni.showToast({ title: "请选择自提点", icon: "none" });
        }
        return;
      }
      if (this.tabActive === 1 && !this.isFreight) {
        uni.showToast({
          title: "该地区暂不支持陪送，可选择自提",
          icon: "none",
        });
        return;
      }
      if (!this.deliveryInfo.userName) {
        uni.showToast({ title: "请输入收货人姓名", icon: "none" });
        return;
      }
      if (!this.deliveryInfo.userPhone) {
        uni.showToast({ title: "请输入收货人手机号", icon: "none" });
        return;
      }
      let param = {
        cartIds: [],
        ticOederAddDTO: {
          postagePrice: this.tabActive === 1 ? Number(this.freight) : 0,
          orderTicketType: "4",
          userId: this.userInfo.userId,
          orderTname: this.userInfo.realName || this.userInfo.nickname,
          orderTphone: this.userInfo.phonenumber,
          shopId: this.list[0].storeId,
          addressDetail: `${this.deliveryInfo.address}@@${
            this.deliveryInfo.addressDetail
          }@@${!!(this.addressInfo.isDefault == "1")}`, // 详细地址
          addressType: this.tabActive, // 是否自提
          deliveryName: this.deliveryInfo.userName, // 收货人姓名
          deliveryPhone: this.deliveryInfo.userPhone, // 收货人手机
        },
        ticOrderDetailAddDTOList: [],
      };
      for (const goods of this.sourceList) {
        if (goods.id) {
          param.cartIds.push(goods.id);
        }
        param.ticOrderDetailAddDTOList.push({
          commonName: goods.storeName,
          goodPic: goods.imgAbbrev,
          orderTicketType: "4",
          ticketCount: goods.goodsNum,
          ticketId: goods.goodsId,
          ticketMoney: goods.price,
          ticketName: goods.name,
          ticketTypeName: goods.type,
        });
      }
      this.isSubmitting = true;
      return addOtherOrder(param).then(({ code, data }) => {
        if (code === 200) {
          if (Number(this.goodsCountPrice) === 0) {
            this.toURL(
              "/page_mall/result/index",
              { state: 1, id: data },
              { type: "redirect" }
            );
            this.isSubmitting = false;
            return;
          }
          return this.getPayOrderInfo(data).finally(() => {
            this.isSubmitting = false;
          });
        } else {
          this.isSubmitting = false;
        }
      });
    },
    formatData(list) {
      const grouped = list.reduce((acc, item) => {
        if (!acc[item.storeId]) {
          acc[item.storeId] = {
            storeId: item.storeId,
            storeName: item.storeName,
            goods: [],
          };
        }
        acc[item.storeId].goods.push({
          ...item,
          toShowPrice: Number(`${item.price}e-2`).toFixed(2),
        });
        return acc;
      }, []);

      return Object.values(grouped);
    },
    getFreight() {
      return getOneByCode(
        {
          city: this.addressInfo.city,
          county: this.addressInfo.county,
          province: this.addressInfo.province,
        },
        { custom: { toast: false } }
      ).then(({ code, data }) => {
        this.isFreight = code === 200;
        if (code !== 200) {
          this.freight = 0;
        }
        this.freight = data.cost;
      });
    },
    changeTab({ id }) {
      this.tabActive = id;
    },
    // 支付前获取订单详细
    getPayOrderInfo(orderId) {
      return payTransactions(orderId)
        .then(() => {
          this.toURL(
            "/page_mall/result/index",
            { state: 1, id: orderId },
            { type: "redirect" }
          );
        })
        .catch(({ code }) => {
          this.toURL(
            "/page_mall/result/index",
            { state: 0, id: orderId },
            { type: "redirect" }
          );
        });
    },
    getAddressList() {
      return getAddressList({
        pageNum: 1,
        pageSize: 100,
      }).then(({ code, rows: lists }) => {
        if (code !== 200) {
          lists = [];
        }
        if (this.selectAddress.id) {
          this.addressInfo =
            lists.find((item) => {
              return item.id == this.selectAddress.id;
            }) || {};
        } else {
          this.addressInfo =
            lists.find((item) => {
              return item.isDefault == "1";
            }) || {};
        }
      });
    },
    getPickUpList() {
      return getPickUpList({
        _id: this.list[0].storeId,
      }).then(({ code, data: lists }) => {
        if (code !== 200) {
          lists = [];
        }
        if (this.selectPickUpPoint.id) {
          this.pickUpInfo =
            lists.find((item) => {
              return item.id == this.selectPickUpPoint.id;
            }) || {};
        } else {
          this.pickUpInfo = lists[0] || {};
        }
      });
    },
  },
};
</script>

<template>
  <view>
    <view class="settle-box">
      <view class="settle-type-box">
        <view class="tabs">
          <tabs
            :list="tabs"
            line-color="#ff5000"
            line-width="48rpx"
            line-height="4rpx"
            :item-style="{
              height: '96rpx',
              padding: '24rpx 20rpx',
              'align-items': 'flex-end',
            }"
            :active-style="{
              'font-size': '36rpx',
              'font-weight': 600,
              color: 'rgba(0, 0, 0, 0.9)',
              'line-height': '48rpx',
            }"
            :inactive-style="{
              'font-size': '28rpx',
              'font-weight': 600,
              color: 'rgba(0, 0, 0, 0.7)',
              'line-height': '40rpx',
            }"
            @change="changeTab"
          ></tabs>
        </view>
        <view
          class="mail"
          v-if="tabActive === 1"
          @click="toURL('/page_my/address/index?form=settle')"
        >
          <view v-if="addressInfo.id">
            <view class="address">
              {{
                addressInfo.provinceName +
                addressInfo.cityName +
                addressInfo.countyName
              }}
              <text class="isDefault" v-if="addressInfo.isDefault == '1'">
                默认
              </text>
            </view>
            <view class="address-desc">
              <view>{{ addressInfo.address }}</view>
              <view class="go-change">
                <u-image
                  src="https://ltjt.sjzballsportpark.com/statics/tyc/static/icon-go1.png"
                  width="32rpx"
                  height="32rpx"
                ></u-image>
              </view>
            </view>
            <view>
              <text class="name">{{ addressInfo.name }}</text>
              <text class="phone">{{ addressInfo.phone }}</text>
            </view>
          </view>
          <view class="no-address-box" v-else>
            <view class="left-box">
              <view style="width: 48rpx; height: 48rpx; flex: none">
                <u-image
                  src="https://ltjt.sjzballsportpark.com/statics/tyc/static/icon-add-orange.png"
                  width="48rpx"
                  height="48rpx"
                ></u-image>
              </view>
              <text class="add-txt">添加地址</text>
            </view>
            <u-image
              src="https://ltjt.sjzballsportpark.com/statics/tyc/static/icon-go1.png"
              width="32rpx"
              height="32rpx"
            ></u-image>
          </view>
        </view>
        <view class="pick-up" v-else>
          <view class="address-desc">
            <view class="pick-up-text">自提点</view>
            <view
              class="flex-between-content"
              @click="
                toURL('/page_my/pickUpPoint/index', { id: list[0].storeId })
              "
            >
              <view class="adress-text u-line-2">
                {{
                  pickUpInfo.provinceName +
                  pickUpInfo.cityName +
                  pickUpInfo.countyName +
                  pickUpInfo.address
                }}
              </view>
              <view class="go-change">
                <u-image
                  src="https://ltjt.sjzballsportpark.com/statics/tyc/static/icon-go1.png"
                  width="32rpx"
                  height="32rpx"
                ></u-image>
              </view>
            </view>
          </view>
          <view class="reserved-information-box">
            <view class="yuliu-text">预留信息</view>
            <view
              class="flex-between-content"
              @click="toURL('/page_my/reserved/index', { id: list[0].storeId })"
            >
              <view
                class="information-box"
                v-if="pickUpUserInfo.name && pickUpUserInfo.phone"
              >
                <view class="name">{{ pickUpUserInfo.name }}</view>
                <view class="phone">{{ pickUpUserInfo.phone }}</view>
              </view>
              <view v-else class="information-box">请选择</view>
              <view class="go-change">
                <u-image
                  src="https://ltjt.sjzballsportpark.com/statics/tyc/static/icon-go1.png"
                  width="32rpx"
                  height="32rpx"
                ></u-image>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="shop-info" v-for="store in list" :key="store.storeId">
        <view class="shop-left" v-if="false">
          <view class="shop-avatar"></view>
          <text class="shop-title">{{ store.storeName }}</text>
        </view>
        <view class="goods-list">
          <view class="info-box" v-for="goods in store.goods" :key="goods.id">
            <view class="left">
              <u-image
                :src="img_api + goods.imgAbbrev"
                width="160rpx"
                height="160rpx"
                radius="12rpx"
              ></u-image>
            </view>
            <view class="right">
              <view class="title">{{ goods.name }}</view>
              <view class="shop-desc" v-if="goods.type">{{ goods.type }}</view>
              <view class="price-num-box">
                <view class="num">x {{ goods.goodsNum }}</view>
                <view class="price">¥{{ goods.toShowPrice }}</view>
              </view>
            </view>
          </view>
        </view>
        <view class="freight-box" v-if="tabActive === 1">
          <view class="freight-label">运费</view>
          <view class="freight-text" v-if="isFreight">
            ¥{{ toShowFreight }}
          </view>
          <view class="freight-text" v-else>--</view>
        </view>
      </view>
    </view>
    <view class="btn-box">
      <view class="count-price-box">
        <view class="count-label">共{{ goodsCountNum }}件</view>
        <view class="count-box">
          <text>总计</text>
          <text class="count-value">¥{{ goodsCountPrice }}</text>
        </view>
      </view>
      <view class="go-pay" @click="placeOrder">提交订单</view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.settle-box {
  margin: 24rpx 32rpx 0;
  padding-bottom: calc(24rpx + 124rpx + env(safe-area-inset-bottom));
}

.settle-type-box {
  background: #faf9f8;
  border-radius: 16rpx;

  .tabs {
    display: flex;
    align-items: center;
    padding: 0 12rpx;
    border-bottom: 2rpx solid rgba(0, 0, 0, 0.1);

    &::v-deep {
      .u-tabs__wrapper__nav__line {
        border-radius: 4rpx 4rpx 0 0;
        bottom: 0;
      }
    }
  }

  .mail {
    min-height: 108rpx;
    padding: 24rpx;
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;

    .address {
      font-size: 24rpx;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.7);
      line-height: 32rpx;
      padding-bottom: 10rpx;
    }

    .isDefault {
      margin-left: 18rpx;
      font-size: 24rpx;
      font-weight: 400;
      color: #fff201;
      line-height: 32rpx;
      padding: 0 8rpx;
      background: #ff5000;
      border-radius: 2rpx;
    }

    .address-desc {
      font-size: 32rpx;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.8);
      line-height: 40rpx;
      padding-bottom: 26rpx;
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
    }

    .no-address-box {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .left-box {
        display: flex;
        align-items: center;
      }

      .add-txt {
        font-size: 32rpx;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.8);
        line-height: 44rpx;
        margin-left: 4rpx;
      }
    }
  }

  .name {
    font-size: 28rpx;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.7);
    line-height: 40rpx;
    padding-right: 24rpx;
  }

  .phone {
    font-size: 28rpx;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.7);
  }

  .go-change {
    flex: none;
    width: 32rpx;
    height: 40rpx;
    display: flex;
    align-items: center;
  }

  .flex-between-content {
    display: flex;
    justify-content: space-between;
    flex: 1;
  }

  .pick-up {
    padding: 24rpx;

    .pick-up-text {
      width: 136rpx;
      font-size: 28rpx;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.5);
      line-height: 40rpx;
    }

    .address-desc {
      display: flex;
      align-items: self-start;
      font-size: 32rpx;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.8);
      line-height: 40rpx;
      padding-bottom: 24rpx;

      .adress-text {
        width: 442rpx;
        font-size: 28rpx;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.8);
        line-height: 40rpx;
        margin-right: 26rpx;
      }
    }

    .reserved-information-box {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .yuliu-text {
        width: 136rpx;
        font-size: 28rpx;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.5);
        line-height: 40rpx;
      }

      .information-box {
        display: flex;
        align-items: center;
      }

      .name {
        font-size: 28rpx;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.8);
        line-height: 40rpx;
      }

      .phone {
        font-size: 28rpx;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.8);
        line-height: 40rpx;
      }
    }
  }
}

.shop-info {
  margin-top: 32rpx;

  .shop-left {
    display: flex;
    margin-bottom: 32rpx;
    padding: 4rpx 0;
  }

  .shop-avatar {
    width: 40rpx;
    height: 40rpx;
    margin-right: 16rpx;
  }

  .shop-title {
    font-size: 28rpx;
    font-weight: 400;
    color: #777f8f;
    line-height: 40rpx;
  }

  .info-box {
    display: flex;
    align-items: center;
    padding: 40rpx 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);

    &:last-of-type {
      border-bottom: none;
    }
  }

  .left {
    flex: none;
    width: 160rpx;
    height: 160rpx;
    margin-right: 24rpx;
  }

  .right {
    flex: auto;
    height: 160rpx;
    display: flex;
    flex-flow: column nowrap;

    .title {
      font-size: 32rpx;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.8);
      line-height: 44rpx;
    }

    .shop-desc {
      background: #f9f4f2;
      padding: 4rpx 8rpx;
      border-radius: 2rpx;
      font-size: 24rpx;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.5);
      line-height: 32rpx;
      margin-top: 16rpx;
      align-self: flex-start;
    }

    .price-num-box {
      height: 44rpx;
      margin-top: auto;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .num {
      font-size: 32rpx;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.7);
      line-height: 44rpx;
    }

    .price {
      font-size: 32rpx;
      font-weight: 700;
      color: rgba(0, 0, 0, 0.8);
      font-family: D-DIN-Bold;
      line-height: 34rpx;
      padding-top: 2rpx;
    }
  }

  .freight-box {
    margin-left: 184rpx;
    padding: 40rpx 0;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: space-between;

    .freight-label {
      font-size: 28rpx;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.5);
      line-height: 40rpx;
    }

    .freight-text {
      font-size: 32rpx;
      font-weight: 700;
      color: rgba(0, 0, 0, 0.8);
      line-height: 34rpx;
      padding-top: 2rpx;
    }
  }
}

.btn-box {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: calc(124rpx + env(safe-area-inset-bottom));
  background: #ffffff;
  box-shadow: 0 14rpx 58rpx 0 rgba(100, 100, 111, 0.2);
  padding: 0 32rpx env(safe-area-inset-bottom);
  display: flex;
  align-items: center;

  .count-price-box {
    margin-right: auto;
    font-size: 24rpx;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.7);
    line-height: 34rpx;
    height: 80rpx;
    display: flex;
    justify-content: space-between;
    flex-flow: column nowrap;
    align-items: flex-start;

    .count-label {
      color: rgba(0, 0, 0, 0.5);
    }

    .count-box {
      display: flex;
      align-items: center;

      .count-value {
        font-size: 40rpx;
        font-family: D-DIN-Bold;
        font-weight: 700;
        color: #ff5000;
        line-height: 44rpx;
        margin-left: 16rpx;
      }
    }
  }

  .go-pay {
    width: 240rpx;
    height: 80rpx;
    background: #ff5000;
    border-radius: 44rpx;
    font-size: 28rpx;
    font-weight: 500;
    color: #ffffff;
    line-height: 40rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
